<template>
    <div>
        <element-tip :selectPort="selectPort" :dialogParams="dialogParams" :shelfParams="shelfParams"></element-tip>
        <div>
            <el-switch
               v-model="switchValue2"
               active-color="#13ce66"
               inactive-color="#ff4949"
               :active-text="$t('OpenAdsorption')"
               :inactive-text="$t('CloseAdsorption')"
            @change="adsorptionSwitch">
            </el-switch>

            <el-button-group style="margin-left:30%">
                <el-button type="primary" plain  @click="nodeUp" icon="el-icon-arrow-up"></el-button>
                <el-button type="primary" plain @click="nodeDown" icon="el-icon-arrow-down"></el-button>
                <el-button type="primary" plain @click="nodeLeft"  icon="el-icon-arrow-left"></el-button>
                <el-button type="primary" plain  @click="nodeRight"  icon="el-icon-arrow-right"></el-button>
            </el-button-group>
        </div>
        <div style="background-color:#f8f8f8; padding-top: 5px;padding-bottom: 5px" align="center">



            <div>

                <el-menu default-active="1" class="el-menu-demo" mode="horizontal">
                    <el-tooltip class="item" effect="dark" :content="$t('LoadChassis')" placement="top-start">
                        <el-menu-item v-if="!onlyCard" index="1">
                            <i class="el-icon-picture"></i>

                            <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage"/>
                        </el-menu-item>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" :content="$t('LoadCard')" placement="top-start">
                        <el-menu-item v-if="!onlyCard" index="2" @click="openAddCardDialog">
                            <i class="el-icon-picture-outline"></i>
                        </el-menu-item>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" :content="$t('LoadCard')" placement="top-start">
                        <el-menu-item v-if="onlyCard" index="2">
                            <i class="el-icon-picture-outline"></i>
                            <input class="crop-input" type="file" ref="cardImg" name="image" accept="image/*"
                                   @change="addOneCardImg"/>
                        </el-menu-item>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" :content="$t('AddPort')" placement="top-start">
                        <el-menu-item index="3" @click="openAddPortImgDialog">
                            <template slot="title">
                                <i class="el-icon-news"></i>
                            </template>
                        </el-menu-item>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" :content="$t('AddLed')" placement="top-start">
                        <el-menu-item index="4" @click="openAddLedDialog">
                            <i class="el-icon-bell"></i>
                        </el-menu-item>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" :content="$t('AddPower')" placement="top-start">
                        <el-menu-item index="5" @click="openAddPowerDialog">
                            <i class="el-icon-circle-plus-outline"></i>
                        </el-menu-item>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" :content="$t('UploadImg')" placement="top-start">
                        <el-menu-item index="6" @click="openUploadDialog">
                            <i class="el-icon-upload"></i>
                        </el-menu-item>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" :content="$t('GenerateFile')" placement="top-start">
                        <el-menu-item v-show="!onlyCard && shelfParams.Image != ''" index="7" @click="generate">
                            <i class="el-icon-setting"></i>
                        </el-menu-item>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" :content="$t('GenerateFile')" placement="top-start">
                        <el-menu-item v-show="onlyCard && cardGroup.length > 0" index="7" @click="generate">
                            <i class="el-icon-setting"></i>
                        </el-menu-item>
                    </el-tooltip>
                </el-menu>

                <div>

                    <el-row type="flex" class="row-bg" justify="center">

                        <el-col :span="24" v-if="!onlyCard" >
                            <div style="overflow:scroll;">
                               <div class="nui-scroll" ref="myCanvas" v-show="isLoadChassis"
                                 :style="'width:'+img.imgWidth+';height:'+img.imgHeight+';backgroundImage:url('+img.imgSrc+');background-repeat:no-repeat;'">

                                </div>
                            </div>
                            <!--<div ref="init" v-show="!isLoadChassis"-->
                            <!--style="border:1px dashed #969696;width:100%;height:200px;">-->

                            <!--</div>-->
                        </el-col>
                        <el-col :span="24"  v-if="onlyCard" >
                            <!-- <el-scrollbar style="height:500px;width:1000px">-->
                            <div style="overflow:scroll;">
                            <div class="nui-scroll"  ref="myCanvas"
                                 :style="'width:'+img.imgWidth+';height:'+img.imgHeight+';backgroundImage:url('+img.imgSrc+');background-repeat:no-repeat;'">

                            </div>
                            </div>
                            <!--</el-scrollbar>-->
                        </el-col>
                    </el-row>
                </div>

            </div>

        </div>
        <add-port-dialog ref="addPort" :addPortDialog="addPortDialog"></add-port-dialog>
        <add-led-dialog :addLedDialog="addLedDialog"></add-led-dialog>
        <add-power-dialog ref="addPower" :addPowerDialog="addPowerDialog"></add-power-dialog>
        <add-card-dialog :addCardDialog="addCardDialog"></add-card-dialog>
        <upload-img-dialog :addUploadDialog="addUploadDialog"></upload-img-dialog>

            <!--<input type="text" @keyup.up="nodeUp()">-->
            <!--<input type="text" @keyup.down="nodeDown()">-->
            <!--<input type="text" @keyup.left="nodeLeft()">-->
            <!--<input type="text" @keyup.right="nodeRight()">-->
    </div>
</template>

<script>
    import zrender from 'zrender'
    import ElementTip from './draw_chassis/elementTip'

    var convert = require('xml-js');

    import AddPortDialog from './draw_chassis/AddPortDialog'
    import AddLedDialog from './draw_chassis/AddLedDialog'
    import AddPowerDialog from "./draw_chassis/AddPowerDialog";
    import AddCardDialog from "./draw_chassis/AddCardDialog";
    import UploadImgDialog from "./draw_chassis/UploadImgDialog";
    export default {
        components: {UploadImgDialog, AddCardDialog, AddPowerDialog, AddLedDialog, AddPortDialog, ElementTip},
        props: {
            onlyCard: false,
            shelfParams: {},
        },
        data: function () {
            let dialog_w = 300;
            let dialog_h = 500;
            return {
                dialogParams: {
                    w: dialog_w,
                    h: dialog_h,
                    x: window.innerWidth / 2 - 57,
                    y: 140 - window.innerHeight / 2,
                    visible: false,
                },
                defaultSrc: './static/img/img.jpg',
                img: {//背景图片
                    imgSrc: '',
                    imgWidth: '100%',
                    imgHeight: '200px'
                },
                dialogVisible: false,
                addPortDialog: false,
                addLedDialog: false,
                addPowerDialog: false,
                addCardDialog: false,
                addUploadDialog: false,
                zr: '',//zrender
                port: {//将要添加的port
                    width: 30,
                    height: 30,
                    radius: 12,
                },
                // shelfParams: {
                //     Image: '',
                //     IsPolling: 'false',
                //     CardPollingTime: '1800000',
                //     PortPollingTime: '30000',
                //     Title: '',
                //     ShelfName: '',
                //     SlotDIF: '0',
                //
                //     CardMenu: [],
                //     PortMenu: [],
                // },
                selectPort: {//选中的port
                    id: "",
                    x: 0,
                    y: 0,
                    width: 0,
                    height: 0,
                    type: undefined,//card port led
                    num: '',//portNum ledNum cardNum,
                    portType: 0,// portType cardType ledType
                    isMenus: 'false',//private card
                    CardMenu: [],//private card
                    PortMenu: [],//private card
                },
                isMouseDown: false,
                group: [],//图中所有对象
                portGroup: [],//图中所有端口对象
                cardGroup: [],//图中所有板卡对象
                ledGroup: [],//图中所有Led对象
                powerGroup: [],//图中所有Power对象
                xlineGroup: {},//x辅助线
                ylineGroup: {},//y辅助线
                showLineDis: 20,//显示线的距离
                defaultAdsorptionDis:8,//初始吸附组件的像素距离
                adsorptionDis: 0,//吸附组件的像素距离
                isLoadChassis: false,
                switchValue1: true,
                switchValue2: true,
                maxWidth:0,
                maxHeight:0,
                adsorpTime:0.5,//判断鼠标按下吸附时间
                mouseDownTimeStamp:0,//鼠标按下时间
                mouseUpTimeStamp:0,//鼠标抬起时间
                adsorpFlagX:false,
                adsorpFlagY:false
            }
        },
        methods: {
            adsorptionSwitch(){
                let vm = this;
                for (var index in vm.group.children()) {
                    let node = vm.group.children()[index]
                        node.attr("style", {opacity: 1})
                }
                vm.selectPort.id = null;

                if(vm.switchValue2){
                    vm.adsorptionDis=vm.defaultAdsorptionDis;
                } else{
                    vm.adsorptionDis=0;
                }
            },
            setImage(e) {
                let vm = this;
                document.onkeydown = function(e){
                    var key = e.keyCode;
                    if(key == 38){
                        vm.nodeUp();
                        e.preventDefault();
                    }else if(key == 40){
                        vm.nodeDown();
                        e.preventDefault();
                    }else if(key == 37){
                        vm.nodeLeft();
                        e.preventDefault();
                    }else if(key == 39){
                        vm.nodeRight();
                        e.preventDefault();
                    }

                }
                const file = e.target.files[0]
                if (!file.type.includes('image/')) {
                    return
                }
                let fileName = file.name;
                let name = fileName.substring(0, fileName.lastIndexOf('.'));
                vm.shelfParams.Image = fileName;
                vm.shelfParams.Title = name;
                const reader = new FileReader()
                reader.onload = event => {
                    vm.img.imgSrc = event.target.result
                    let img = new Image()
                    img.src = vm.img.imgSrc;
                    img.onload = function () {
                        vm.img.imgWidth = img.width + 'px';
                        vm.img.imgHeight = img.height + 'px';
                        vm.zr.resize({
                            width: vm.img.imgWidth,
                            height: vm.img.imgHeight,
                        });
                    }
                    vm.isLoadChassis = true;
                }
                reader.readAsDataURL(file);
            },
            openAddPortImgDialog() {
                this.addPortDialog = true;
            },
            openAddLedDialog() {
                this.addLedDialog = true;
            },
            openAddPowerDialog() {
                this.addPowerDialog = true;
            },
            openAddCardDialog() {
                this.addCardDialog = true;
            },
            openUploadDialog() {
                this.addUploadDialog = true;
            },
            addOneCardImg(e) {
                let vm = this;
                document.onkeydown = function(e){
                    var key = e.keyCode;
                    if(key == 38){
                        vm.nodeUp();
                        e.preventDefault();
                    }else if(key == 40){
                        vm.nodeDown();
                        e.preventDefault();
                    }else if(key == 37){
                        vm.nodeLeft();
                        e.preventDefault();
                    }else if(key == 39){
                        vm.nodeRight();
                        e.preventDefault();
                    }

                }
                let file = e.target.files[0];
                if (!file.type.includes('image/')) {
                    return
                }
                let fileName = file.name;
                const reader = new FileReader();
                reader.onload = event => {
                    let img = new Image()
                    img.src = event.target.result;
                    img.onload = function () {
                        if(img.width> vm.maxWidth) {
                            vm.maxWidth = img.width+100;
                            vm.img.imgWidth =  vm.maxWidth+'px';
                        }
                        vm.maxHeight = vm.maxHeight + img.height;
                        // if( vm.maxHeight >600 ) {
                        //     vm.img.maxHeight = 600;
                        // }
                        vm.img.imgHeight =  vm.maxHeight+'px';
                        vm.zr.resize({
                            width: vm.img.imgWidth,
                            height: vm.img.imgHeight,
                        });
                        vm.addImg(vm.cardGroup, img.width, img.height, img.src, fileName, 'card')
                        vm.$refs.cardImg.value = '';
                    }
                }
                reader.readAsDataURL(file);
            },
            addImg(tmpGroup, imgW, imgH, portImg, imgName, imgType, num, portType) {
                let vm = this;
                let aaa = new zrender.Image({
                    style: {
                        imgName: imgName,
                        image: portImg,
                        x: 0,
                        y: 0,
                        width: imgW,
                        height: imgH,
                        type: imgType,
                        num: num,
                        portType: portType,
                    },
                    draggable: true
                }).on('mousemove', function () {//选中事件
                    vm.dragNode(aaa, tmpGroup);
                }).on('mousedown', function () {//选中事件
                    vm.mouseDownTimeStamp =  (new Date()).getTime();
                    vm.selectNode(aaa);
                }).on('mouseup', function () {//选中事件
                    vm.mouseUpTimeStamp =  (new Date()).getTime();
                    if(vm.mouseUpTimeStamp - vm.mouseDownTimeStamp>vm.adsorpTime * 1000)
                        vm.adsorpNode(aaa,tmpGroup);
                })
                tmpGroup.push(aaa);
                vm.group.add(aaa);


            },
            dragNode(aaa, tmpGroup) {
                let vm = this;
                if (aaa.id == vm.selectPort.id) {
                    let x = aaa.position[0];
                    let y = aaa.position[1];
                    vm.selectPort.x = x;
                    vm.selectPort.y = y;
                    vm.selectPort.width = aaa.style.width;
                    vm.selectPort.height = aaa.style.height;
                    for (var index in tmpGroup) {
                        let node = tmpGroup[index];
                        let valueX = node.position[0];
                        let valueY = node.position[1];
                        let difx = Math.abs(valueX - x);
                        let dify = Math.abs(valueY - y);

                        if (vm.isMouseDown) {//辅助线
                            if (aaa.id != node.id && difx < vm.showLineDis) {
                                if (!vm.xlineGroup[valueX]) {
                                    var xline = new zrender.Line({
                                        shape: {
                                            x1: valueX,
                                            y1: 0,
                                            x2: valueX,
                                            y2: vm.img.imgHeight.split("px")[0],
                                        }, style: {
                                            stroke: '#ffffff',
                                            lineDash: [2, 2]
                                        }
                                    })
                                    vm.zr.add(xline);
                                    vm.xlineGroup[valueX] = xline;
                                }
                            }
                            if (aaa.id != node.id && dify < vm.showLineDis) {
                                if (!vm.ylineGroup[valueY]) {
                                    var yline = new zrender.Line({
                                        shape: {
                                            x1: 0,
                                            y1: valueY,
                                            x2: vm.img.imgWidth.split("px")[0],
                                            y2: valueY,
                                        }, style: {
                                            stroke: '#ffffff',
                                            lineDash: [2, 2]
                                        }

                                    })
                                    vm.zr.add(yline);
                                    vm.ylineGroup[valueY] = yline;
                                }
                            }
                        }
                    }
                }
            },
            adsorpNode(aaa, tmpGroup) { //吸附
                let vm = this;
                if (aaa.id == vm.selectPort.id) {
                    let x = aaa.position[0];
                    let y = aaa.position[1];
                    vm.selectPort.x = x;
                    vm.selectPort.y = y;
                    vm.selectPort.width = aaa.style.width;
                    vm.selectPort.height = aaa.style.height;
                    for (var index in tmpGroup) {
                        let node = tmpGroup[index];
                        let valueX = node.position[0];
                        let valueY = node.position[1];
                        let difx = Math.abs(valueX - x);
                        let dify = Math.abs(valueY - y);
                        if (aaa.id != node.id && difx < vm.adsorptionDis && difx > 0) {//吸附
                            vm.changeEleAttr(aaa, valueX, y, aaa.style.width, aaa.style.height);
                        }
                        if (aaa.id != node.id && dify < vm.adsorptionDis && dify > 0) {//吸附
                            vm.changeEleAttr(aaa, x, valueY, aaa.style.width, aaa.style.height);
                        }

                    }
                }
            },
            selectNode(aaa) {
                let vm = this;
                vm.isMouseDown = true
                let x = aaa.position[0];
                let y = aaa.position[1];
                vm.selectPort.id = aaa.id;
                vm.selectPort.x = x;
                vm.selectPort.y = y;
                vm.selectPort.width = aaa.style.width;
                vm.selectPort.height = aaa.style.height;
                vm.selectPort.type = aaa.style.type;
                vm.selectPort.num = aaa.style.num;
                vm.selectPort.portType = aaa.style.portType;
                vm.selectPort.isMenus = aaa.style.isMenus;
                vm.selectPort.CardMenu = aaa.style.CardMenu;
                vm.selectPort.PortMenu = aaa.style.PortMenu;
                for (var index in vm.group.children()) {
                    let node = vm.group.children()[index];
                    if (aaa.id != node.id) {
                        node.attr("style", {opacity: 1})
                    }
                }
                aaa.attr("style", {opacity: 0.5})
            },
            nodeUp(){
                let vm = this;
                if(vm.selectPort.id){
                    vm.selectPort.y = vm.selectPort.y - 1;
                    vm.changeSelectPortPos();
                }
            },
            nodeDown(){
                let vm = this;
                if(vm.selectPort.id){
                    vm.selectPort.y = vm.selectPort.y + 1;
                    vm.changeSelectPortPos();
                }
            },
            nodeLeft(event){
                let vm = this;
                if(vm.selectPort.id){
                    vm.selectPort.x = vm.selectPort.x - 1;
                    vm.changeSelectPortPos();
                }

            },
            nodeRight(){
                let vm = this;
                if(vm.selectPort.id){
                    vm.selectPort.x = vm.selectPort.x + 1;
                    vm.changeSelectPortPos();
                }
            },
            moveSelectPortPos(){
                let vm = this;
                if(vm.selectPort.id){

                }
            },
            changeSelectPortPos() {
                let vm = this;
                let children = vm.group.children();
                for (var index in children) {
                    let node = children[index];
                    if (node.id == vm.selectPort.id) {
                        vm.changeEleAttr(node, vm.selectPort.x, vm.selectPort.y, vm.selectPort.width, vm.selectPort.height, true);
                    }
                }
            },
            deleteSelectPort() {
                let vm = this;
                for (var index in vm.portGroup) {
                    let node = vm.portGroup[index];
                    if (node.id == vm.selectPort.id) {
                        vm.portGroup.splice(index, 1);
                        vm.group.remove(node);
                        return;
                    }
                }
                for (var index in vm.ledGroup) {
                    let node = vm.ledGroup[index];
                    if (node.id == vm.selectPort.id) {
                        vm.ledGroup.splice(index, 1);
                        vm.group.remove(node);
                        return;
                    }
                }
                for (var index in vm.cardGroup) {
                    let node = vm.cardGroup[index];
                    if (node.id == vm.selectPort.id) {
                        vm.cardGroup.splice(index, 1);
                        vm.group.remove(node);
                        return;
                    }
                }
                for (var index in vm.powerGroup) {
                    let node = vm.powerGroup[index];
                    if (node.id == vm.selectPort.id) {
                        vm.powerGroup.splice(index, 1);
                        vm.group.remove(node);
                        return;
                    }
                }
            },
            changeEleAttr(node, x, y, w, h, active) {
                let vm = this
                let style = {};
                style.width = parseInt(w);
                style.height = parseInt(h);
                if (active) {
                    style.num = vm.selectPort.num;
                    style.portType = vm.selectPort.portType;
                    style.isMenus = vm.selectPort.isMenus;
                    style.CardMenu = vm.selectPort.CardMenu;
                    style.PortMenu = vm.selectPort.PortMenu;
                    console.log(style)
                }

                node.attr({
                    position: [parseInt(x), parseInt(y)],
                    style: style,
                });
            },
            generate() {
                let reqData = {}
                let vm = this;
                // console.log(vm.shelfParams.PortMenu)
                // return
                if (!vm.onlyCard) {
                    if (vm.shelfParams.Image == '') {
                        return
                    }
                    let shelfObj = vm.generateShelf();
                    let shelfXml = convert.js2xml(shelfObj, {compact: true});
                    reqData.shelf = {
                        shelfName: vm.shelfParams.Title + 'Shelf',
                        shelfXml: shelfXml,
                    };
                }

                let cardObjs = vm.generateCards();
                reqData.cards = [];
                for (var index in cardObjs) {
                    let cardXml = convert.js2xml(cardObjs[index], {compact: true});
                    let card = {
                        cardName: vm.shelfParams.Title + '_Card' + cardObjs[index].Card._attributes.CardType,
                        cardXml: cardXml,
                    }
                    reqData.cards.push(card)
                }
                vm.$http
                    .post('chassis/createChassis', {
                        chassis: JSON.stringify(reqData)
                    })
                    .then(function (response) {
                        if (response.data.result) {
                            // vm.$message({
                            //     message: vm.$t('Success'),
                            //     type: 'success'
                            // });
                            vm.$confirm('文件已生成，是否下载', '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'success'
                            }).then(() => {

                                let map = response.data.result;
                                for (var index in map){
                                    let path = map[index];
                                    vm.$http({
                                        params : {
                                            path : path,
                                            fileName : index + '@~',
                                        },
                                        method : 'get',
                                        url : 'chassis/downloadFile',
                                        responseType : 'blob',
                                    }).then((response) => {
                                        if (!response) {
                                            return
                                        }
                                        let url = window.URL.createObjectURL(response.data)
                                        let link = document.createElement('a')
                                        link.style.display = 'none'
                                        link.href = url
                                        let reqUrl = response.request.responseURL;
                                        // let reg=/(?<=fileName=).*?(?=@~)/g;
                                        // let fileName = reg.exec(reqUrl);
                                        let fileName = reqUrl.substring(reqUrl.indexOf('fileName='), reqUrl.indexOf('@~')).split('=')[1];
                                        link.setAttribute('download', fileName)
                                        document.body.appendChild(link)
                                        link.click()
                                    })
                                }

                            }).catch(() => {

                            });



                        } else {
                            vm.$message.error(vm.$t('Failed'));
                        }
                    })
                    .catch(function (error) {
                        vm.$message.error('ERR_CONNECTION_REFUSED');
                        console.log(error)
                    })
            },
            generateShelf() {
                let vm = this;
                //生成shelf
                let sObj = {};
                sObj.Shelf = {};
                //attr
                let shelfAttr = {};
                let mrdRoot = 'images/';
                shelfAttr.Image = mrdRoot + vm.shelfParams.Image;
                shelfAttr.IsPolling = vm.shelfParams.IsPolling;
                shelfAttr.CardPollingTime = vm.shelfParams.CardPollingTime;
                shelfAttr.PortPollingTime = vm.shelfParams.PortPollingTime;
                shelfAttr.Title = vm.shelfParams.Title;
                shelfAttr.ShelfName = vm.shelfParams.ShelfName;
                shelfAttr.SlotDIF = vm.shelfParams.SlotDIF;
                sObj.Shelf._attributes = shelfAttr;

                //slots
                let shelfSlots = []
                let slotCnt = 0;
                sObj.Shelf.Slots = shelfSlots;
                if (vm.cardGroup.length > 0) {
                    for (var index in vm.cardGroup) {
                        let slots = {}
                        let slotsAttr = {};
                        slots._attributes = slotsAttr;
                        shelfSlots.push(slots)

                        let node = vm.cardGroup[index];
                        slotsAttr.Image = node.style.imgName;
                        if (node.style.portType != undefined && node.style.portType != '') {
                            slotsAttr.CartType = node.style.portType;
                        }
                        slotsAttr.CardNum = node.style.num ? node.style.num : parseInt(index) + 1;
                        slotsAttr.X = node.position[0];
                        slotsAttr.Y = node.position[1];
                        slotsAttr.W = node.style.width;
                        slotsAttr.H = node.style.height;

                        slotCnt++;
                    }
                    shelfSlots.sort((a, b) => {
                        return parseInt(a._attributes.CardNum) - parseInt(b._attributes.CardNum)
                    })
                } else {
                    let slots = {}
                    let slotsAttr = {};
                    slots._attributes = slotsAttr;
                    shelfSlots.push(slots)
                    slotsAttr.Image = '';
                    slotsAttr.X = 0;
                    slotsAttr.Y = 0;
                    slotsAttr.W = vm.img.imgWidth;
                    slotsAttr.H = vm.img.imgHeight;

                    slotCnt++;
                }
                shelfAttr.SlotCount = slotCnt;

                //power
                let shelfPIcons = []
                sObj.Shelf.PIcons = shelfPIcons;
                if (vm.powerGroup.length > 0) {
                    for (var index in vm.powerGroup) {
                        let PIcon = {}
                        let PIconsAttr = {};
                        PIcon._attributes = PIconsAttr;
                        shelfPIcons.push(PIcon)

                        let node = vm.powerGroup[index];
                        PIconsAttr.Image = node.style.imgName;
                        PIconsAttr.PowerNum = node.style.num ? node.style.num : parseInt(index) + 1;
                        PIconsAttr.X = node.position[0];
                        PIconsAttr.Y = node.position[1];
                        PIconsAttr.W = node.style.width;
                        PIconsAttr.H = node.style.height;
                    }
                    shelfPIcons.sort((a, b) => {
                            return parseInt(a._attributes.PowerNum) - parseInt(b._attributes.PowerNum)
                        }
                    )
                }

                return sObj;
            },
            generateCards() {
                let vm = this;
                //生成card
                let cardObjs = [];
                if (vm.cardGroup.length > 0) {
                    for (var index in vm.cardGroup) {
                        let node = vm.cardGroup[index];
                        if (node.style.portType == undefined || node.style.portType == '') {
                            continue;
                        }
                        vm.generateCard(cardObjs, node)
                    }
                }
                else {
                    let node = {
                        style: {
                            imgName: vm.shelfParams.Image,
                            portType: 1,
                            isMenus: true,
                        },
                        position: [0, 0]
                    };

                    vm.generateCard(cardObjs, node, true)
                }
                return cardObjs;
            },
            generateCard(cardObjs, node, contained) {
                let vm = this
                let cardObj = {}
                cardObjs.push(cardObj);
                cardObj.Card = {};
                //attr
                let cardAttr = {};
                cardObj.Card._attributes = cardAttr;
                let mrdRoot = 'images/';
                cardAttr.Image = mrdRoot + node.style.imgName;
                cardAttr.CardType = node.style.portType;
                let X = node.position[0];
                let Y = node.position[1];

                //port
                let cardPorts = []
                let portCnt = 0;
                cardObj.Card.Ports = cardPorts;
                for (var j in vm.portGroup) {
                    let port = vm.portGroup[j];
                    if (contained || node.rectContain(port.position[0], port.position[1])) {
                        let ports = {}
                        let portsAttr = {};
                        ports._attributes = portsAttr;
                        cardPorts.push(ports)

                        portsAttr.Image = mrdRoot + port.style.imgName;
                        portsAttr.PortType = port.style.portType;
                        portsAttr.PortNum = port.style.num;
                        portsAttr.X = port.position[0] - X;
                        portsAttr.Y = port.position[1] - Y;
                        portsAttr.W = port.style.width;
                        portsAttr.H = port.style.height;

                        portCnt++;
                    }
                }
                cardAttr.PortCount = portCnt;


                //port
                let cardLeds = []
                cardObj.Card.Led = cardLeds;
                for (var j in vm.ledGroup) {
                    let port = vm.ledGroup[j];
                    if (contained || node.rectContain(port.position[0], port.position[1])) {
                        let led = {}
                        let ledAttr = {};
                        led._attributes = ledAttr;
                        cardLeds.push(led)

                        ledAttr.LedType = port.style.portType;
                        ledAttr.LedNum = port.style.num;
                        ledAttr.X = port.position[0] - X;
                        ledAttr.Y = port.position[1] - Y;
                        ledAttr.W = port.style.width;
                        ledAttr.H = port.style.height;
                    }
                }

                //menus
                if (node.style.isMenus) {
                    let cardMenuGroups = []
                    cardObj.Card.MenuGroups = cardMenuGroups;

                    let tempCardGroup = undefined
                    if (node.style.CardMenu && node.style.CardMenu.length > 0) {
                        tempCardGroup = vm.getCardMenu(node.style.CardMenu);
                    } else {
                        tempCardGroup = vm.getCardMenu(vm.shelfParams.CardMenu);
                    }
                    if (tempCardGroup) {
                        cardMenuGroups.push(tempCardGroup)
                    }

                    let portTypes = undefined;
                    if (node.style.PortMenu && node.style.PortMenu.length > 0) {
                        portTypes = node.style.PortMenu;
                    } else {
                        portTypes = vm.shelfParams.PortMenu;
                    }
                    // if (portTypes.length > 0) {
                    //     for (var it in portTypes) {
                    //
                    //         let portType = portTypes[it];
                    //         cardMenuGroups.push(vm.getPortMenu(portType));
                    //     }
                    // }
                    if (portTypes.length > 0) {
                        let type_menus = {};
                        for (var it in portTypes) {
                            let portType = portTypes[it];
                            let type_munu = portType.split('_');
                            if(! type_menus[type_munu[0]]){
                                type_menus[type_munu[0]] = []
                            }
                            type_menus[type_munu[0]].push(type_munu[1])
                            // cardMenuGroups.push(vm.getPortMenu(portType));
                        }
                        for(var type in type_menus){
                            let menus = type_menus[type];
                            cardMenuGroups.push(vm.getPortMenus(type, menus));
                        }
                    }
                }
            },
            getPortMenus(type, menus){
                let menu = {}
                let menuAttr = {};
                menu._attributes = menuAttr;
                menuAttr.PortType = type;

                let menuIterms = [];
                menu.MenuIterm = menuIterms;
                for (var index in menus) {
                    let type = menus[index];
                    let iterm = {}
                    menuIterms.push(iterm);
                    let itermAttr = {};
                    iterm._attributes = itermAttr;
                    switch (type) {
                        case 'PortStatus':
                            itermAttr.Name = 'port status';
                            itermAttr.Classname = 'setPortstatus()';
                            break;
                        case 'PortUPDOWN':
                            itermAttr.Name = 'port updown';
                            itermAttr.Classname = 'setPortupdown()';
                            break;
                    }
                }
                return menu;
            },
            // getPortMenu(type) {
            //     let menu = {}
            //     let menuAttr = {};
            //     menu._attributes = menuAttr;
            //     menuAttr.PortType = type;
            //     let menuIterm = {};
            //     menu.MenuIterm = menuIterm;
            //     let itermAttr = {};
            //     menuIterm._attributes = itermAttr;
            //     itermAttr.Name = 'port status';
            //     itermAttr.Classname = 'setPortstatus()';
            //     return menu;
            // },
            getCardMenu(types) {
                if (types.length == 0) {
                    return;
                }
                let menu = {}
                let menuAttr = {};
                menu._attributes = menuAttr;
                menuAttr.PortType = 'CardMenu';
                let menuIterms = [];
                menu.MenuIterm = menuIterms;
                for (var index in types) {
                    let type = types[index];
                    let iterm = {}
                    menuIterms.push(iterm);
                    let itermAttr = {};
                    iterm._attributes = itermAttr;
                    switch (type) {
                        case 'MenuCardReset':
                            itermAttr.Name = 'MenuCardReset';
                            itermAttr.Classname = 'resetMenuCard()';
                            break;
                        case 'MenuCardDisable':
                            itermAttr.Name = 'MenuCardDisable';
                            itermAttr.Classname = 'setMenuCardDisable()';
                            break;
                        case 'MenuCardEnable':
                            itermAttr.Name = 'MenuCardEnable';
                            itermAttr.Classname = 'setMenuCardEnable()';
                            break;
                    }
                }
                return menu;
            },
            handleError() {
                this.$notify.error({
                    title: '上传失败',
                    message: '图片上传接口上传失败，可更改为自己的服务器接口'
                })
            },
            refreshPowerImg() {
                this.$refs["addPower"].getPowerImgList();
            },
            refreshPortImg() {
                this.$refs["addPort"].getPortImgList();
            }
        },
        created() {

        },
        mounted() {
            var vm = this;
            vm.zr = zrender.init(vm.$refs['myCanvas']);
            vm.group = new zrender.Group();
            vm.zr.on('mousedown', function () {
                vm.isMouseDown = true
            })
            vm.zr.on('mouseup', function () {
                vm.isMouseDown = false;
                //清除辅助线
                for (var index in vm.xlineGroup) {
                    vm.zr.remove(vm.xlineGroup[index]);
                }
                for (var index in vm.ylineGroup) {
                    vm.zr.remove(vm.ylineGroup[index]);
                }
                vm.xlineGroup = {};
                vm.ylineGroup = {};
            })
            vm.zr.add(vm.group);
            vm.adsorptionDis = vm.defaultAdsorptionDis;






        }
    }
</script>

<style scoped>

    .crop-input {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        opacity: 0;
        cursor: pointer;
    }


</style>
